/**
 * 
 */
package org.mhz.ootw.util;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.core.CoreContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

/**
 * @author Mahan
 * 
 * Solr Server factory
 */
public final class SolrServerHelper
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SolrServerHelper.class);
    
    private static EmbeddedSolrServer mSolrServer;
    
    /**
     * Private constructor
     */
    private SolrServerHelper()
    {
        
    }
    
    /**
     * @return The SolrServer
     */
    public static SolrServer getInstance()
    {
        synchronized (SolrServerHelper.class)
        {
            if (mSolrServer == null)
            {
                LOGGER.info("Creating a new instance of SolrServer.");
        
                try
                {
                    final CoreContainer.Initializer initializer = new CoreContainer.Initializer();
                    final CoreContainer coreContainer = initializer.initialize();
                    mSolrServer = new EmbeddedSolrServer(coreContainer, "");
                }
                catch (SAXException saxEx)
                {
                    LOGGER.error("Error initializing SOLR server", saxEx);
                    mSolrServer = null;
                }
                catch (IOException ioEx)
                {
                    LOGGER.error("Error initializing SOLR server", ioEx);
                    mSolrServer = null;
                }
                catch (ParserConfigurationException pcEx)
                {
                    LOGGER.error("Error initializing SOLR server", pcEx);
                    mSolrServer = null;
                }   
            }
        }
        
        return mSolrServer;
    }
}
